package org.net.cms.service.application;

import jakarta.annotation.Resource;
import org.net.cms.controller.app.application.vo.AppApplicationReqVO;
import org.net.cms.dao.ApplicationDto;
import org.net.cms.dao.ParentAccountDto;
import org.net.cms.dao.PaymentDto;
import org.net.cms.dao.StudentDto;
import org.net.cms.enums.StudentApplicationEnums;
import org.net.cms.mapper.ApplicationMapper;
import org.net.cms.mapper.ParentAccountMapper;
import org.net.cms.mapper.StudentMapper;
import org.net.cms.service.payment.PaymentService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApplicationServiceImpl implements ApplicationService {

    @Resource
    private ApplicationMapper applicationMapper;

    @Resource
    private StudentMapper studentMapper;
    
    @Resource
    private ParentAccountMapper parentAccountMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private PaymentService paymentService;


    @Override
    public ApplicationDto getApplication(int id) {
        return applicationMapper.getApplicationById(id);
    }

    @Override
    public List<ApplicationDto> applicationList(int type) {
        // 1 已通过 2 待审核 0不通过
        return applicationMapper.applicationList(type);
    }

    @Override
    public List<ApplicationDto> getMyApplications(String phone) {
        return applicationMapper.getMyApplicationListByPhone(phone);
    }

    @Override
    public int checkStatus(String studentCardId) {
        try {
            int status = applicationMapper.studentApplicationStatus(studentCardId);
            System.out.println("存在状态：" + status);
            return status;
        } catch (Exception e) {
            System.out.println("不存在申请");
            return StudentApplicationEnums.DOES_NOT_EXIST.getStatus();
        }
    }

    @Override
    public Boolean admissionApplication(AppApplicationReqVO studentReqVO) {
        // 设置状态为等待审核
        studentReqVO.setStatus(StudentApplicationEnums.PENDING_APPROVAL.getStatus());
        applicationMapper.addAdmissionApplication(studentReqVO);
        return Boolean.TRUE;
    }

    @Override
    public Boolean checkApplication(int id, int status) {
        applicationMapper.updateStatus(id, status);

        if (status == StudentApplicationEnums.PASS.getStatus()) {
            // 添加学生表信息
            ApplicationDto application = applicationMapper.getApplicationById(id);
            StudentDto studentDto = new StudentDto();
            studentDto.setParentCardId(application.getParentCardId());
            studentDto.setParentPhone(application.getParentPhone());
            studentDto.setStudentCardId(application.getStudentCardId());
            studentDto.setName(application.getName());
            studentDto.setSex(application.getSex());
            studentDto.setBirthday(application.getBirthday());
            studentDto.setDomicile(application.getDomicile());
            studentMapper.addStudent(studentDto);

            // 新增家长账号
            int studentId = studentMapper.getStudentId(application.getStudentCardId());
            // 先查询家长账号是否存在（返回 null 表示无）
            ParentAccountDto parentAccount = parentAccountMapper.getParentAccountByPhone(application.getParentPhone());

            if (parentAccount != null) {
                // 家长账号存在
                System.out.println("找到家长账号: " + parentAccount.getPhone());

                Set<Long> studentSet;
                try {
                    // 解析已有学生列表
                    studentSet = parseStudentList(parentAccount.getStudentList());
                } catch (Exception e) {
                    // 解析失败（比如字段为空、格式错），视为无数据
                    System.out.println("解析 studentList 失败，初始化为空列表");
                    studentSet = new HashSet<>();
                }

                // 添加新学生ID
                studentSet.add((long) studentId);

                // 重新排序并拼接为字符串
                String newStudentList = studentSet.stream()
                        .map(String::valueOf)
                        .sorted()  // 按数字字符串排序
                        .collect(Collectors.joining(","));

                // 更新家长账号
                parentAccountMapper.updateParentAccount(newStudentList, parentAccount.getId());
                System.out.println("已更新家长账号的学生列表: " + newStudentList);

                // 新增缴费记录，默认一创建账号，就新增缴费记录，都是未交费
                // 新增餐费记录
                addPayment(parentAccount.getId(), studentDto);
            } else {
                // 家长账号不存在，创建新账号
                System.out.println("未找到家长账号，创建新账号: " + application.getParentPhone());

                String password = application.getParentCardId().substring(application.getParentCardId().length() - 6);
                String encode = passwordEncoder.encode(password);

                ParentAccountDto newParentAccount = new ParentAccountDto();
                newParentAccount.setParentCardId(application.getParentCardId());
                newParentAccount.setPhone(application.getParentPhone());
                newParentAccount.setPassword(encode); // 密码为身份证后六位并加密
                newParentAccount.setStudentList(String.valueOf(studentId)); // 第一个学生

                int i = parentAccountMapper.addParentAccount(newParentAccount);

                System.out.println("新家长账号创建成功");

                // 自动增加未交费记录
                addPayment(newParentAccount.getId(), studentDto);
            }
        }

        return true;
    }

    private void addPayment(Integer id, StudentDto studentDto) {
        // 新增缴费记录，默认一创建账号，就新增缴费记录，都是未交费
        // 新增餐费记录
        PaymentDto paymentDto = new PaymentDto();
        paymentDto.setParentId(id);
        paymentDto.setStudentId(studentDto.getId());
        paymentDto.setName(studentDto.getName());
        paymentDto.setPayType(0); // 设置餐费
        paymentDto.setAmount(new BigDecimal(0));
        paymentDto.setStatus(0);
        paymentService.save(paymentDto);

        // 新增学费记录
        paymentDto.setPayType(1); // 设置学费
        paymentService.save(paymentDto);

        // 新增活动费记录
        paymentDto.setPayType(2); // 设置活动费
        paymentService.save(paymentDto);
    }

    private Set<Long> parseStudentList(String studentList) {
        Set<Long> studentSet = new HashSet<>();
        if (studentList == null || studentList.trim().isEmpty()) {
            return studentSet;
        }
        String[] ids = studentList.split(",");
        for (String id : ids) {
            studentSet.add(Long.parseLong(id));
        }
        return studentSet;
    }

    @Override
    public Boolean deleteApplication(int id) {
        applicationMapper.deleteAdmission(id);
        return true;
    }

    @Override
    public List<ApplicationDto> getUnbindList(int type) {
        // 4 解绑待审核 5解绑通过 6解绑不通过
        return applicationMapper.applicationList(type);
    }

    @Override
    public Boolean updateUnbindStatus(int id, int status) {
        // id是申请解绑的id
        applicationMapper.updateStatus(id, status);
        if (status == StudentApplicationEnums.UNBIND_PASS.getStatus()) {
            // 如果状态为5通过，将删掉学生信息
            ApplicationDto application = applicationMapper.getApplicationById(id);
            String studentCardId = application.getStudentCardId();
            String parentCardId = application.getParentCardId();

            // 获取学生id
            int studentId = studentMapper.getStudentId(studentCardId);
            int parentId = parentAccountMapper.getParentIdByCardId(parentCardId);

            // 删除家长表中的学生id
            unbindParseStudentList(studentId, parentId);

            // 删除对应学生id的缴费记录
            unbindStudentPayment(studentId);

            // 根据学生身份证号获取学生id并软删除学生信息
            studentMapper.deleteStudent(studentId);

        }
        return Boolean.TRUE;
    }

    private void unbindStudentPayment(int studentId) {
        System.out.println("支付学生id：" + studentId);
        // 删除这个学生的缴费信息
        paymentService.delete(studentId);
    }

    private void unbindParseStudentList(int studentId, int parentId) {
        System.out.println("删除学生id：" + studentId);
        // 删除家长表中的学生id
        String myStudent = parentAccountMapper.getMyStudentById(parentId);

        if (myStudent == null || myStudent.trim().isEmpty()) {
            return ;
        }

        String[] ids = myStudent.split(",");
        int unbindId = 0;
        for (int i = 0; i < ids.length; i++) {
            if (Integer.parseInt(ids[i]) == studentId) {
                unbindId = i;
                break;
            }
        }
        List<String> idList = new ArrayList<>(Arrays.asList(ids));
        idList.remove(unbindId);

        String newIds = String.join(",", idList);

        parentAccountMapper.updateParentAccount(newIds, parentId);
    }

}
